package com.example.mdm4.main

import androidx.lifecycle.viewModelScope
import com.example.lib_base.BaseViewModel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flatMapConcat
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch

class MainViewModel:BaseViewModel<MainRepository,MainState> (){
    override fun createState(): MainState {
        return MainState(false,false, mutableListOf())
    }

    override fun createResp(): MainRepository {
        return MainRepository()
    }

    //获取是否锁屏，以及设备白名单
    fun selWhite(){
        viewModelScope.launch {
            //请求设置设备是否锁屏，flatMapConcat：第二个流是在第一个流请求之后执行的
            comFlow(resp.selLock()).flatMapConcat {
                if(it.statusCode==200){
                    val errorEntity = ErrorEntity()
                    errorEntity.msg=it.msg
                    errorEntity.statusCode=100

                    return@flatMapConcat comFlow(flow { emit(errorEntity) })
                }else{
                    return@flatMapConcat comFlow(resp.selWhite())
                }
            }.collect{
                if(it.statusCode==200){
                    val whiteEntity = it as WhiteEntity
                    mutableContainer.updateUiState { copy(false,true,it.datas) }
                }else{
                    mutableContainer.updateUiState { copy(true,false, mutableListOf()) }
                }
            }
        }
    }
}